package com.nakanomay.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author nakano_may丶
 * @date 2023/4/17
 * @Version 1.0
 * @description
 */
public class ZkClient
{
    // 注意：逗号左右不能有空格
    private String connectString = "172.16.102.100:2181,172.16.102.135:2181,172.16.102.136:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient = null;

    @Before
    public void init() throws IOException
    {
        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher()
        {
            @Override
            public void process(WatchedEvent watchedEvent)
            {
                // 收到事件通知后的回调函数（用户的业务逻辑）
                System.out.println(watchedEvent.getType() + "--" + watchedEvent.getPath());

                // 再次启动监听
                try {
                    List<String> children = zkClient.getChildren("/", true);
                    for (String child : children) {
                        System.out.println(child);
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Test
    public void create() throws InterruptedException, KeeperException
    {
        /**
         * 参数1：要创建的节点的路径
         * 参数2：节点数据
         * 参数3：节点权限
         * 参数4：节点的类型
         */
        String nodeCreated = zkClient.create("/atguigu", "ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void getChildren() throws Exception
    {
        List<String> children = zkClient.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void exist() throws Exception
    {
        Stat stat = zkClient.exists("/atguigu", true);
        System.out.println(stat == null ? "not exist" : "exist");
    }
}
